<template>
  <div class="course-container mx-center">
    <!-- 搜索模块 -->
    <div class="course-search">
      <div class="search-tag">
        课程管理
      </div>
      <div class="search-wrapper">
        <input v-model="query.title" @keyup.enter="fetchData" type="text" placeholder="输入课程标题搜索">
        <i @click="fetchData" class="iconfont">&#xe63c;</i>
      </div>
      <el-button v-if="userInfo.identity == 'vip'" @click="handleCreate" style="float: right;margin: 18px;" type="primary" size="mini">添加</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      size="mini"
      highlight-current-row
    >
      <el-table-column label="标题">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="图片" width="130" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.img" width="100px" height="60px">
        </template>
      </el-table-column>
      <el-table-column label="作者" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="难度" width="110" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.rank }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.tagTitle }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="140" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center">
        <template slot-scope="scope">
          <el-tag type="primary" size="mini" v-for="tag in scope.row.tags.split(',')">{{tag}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary"  v-if="userInfo.identity == 'vip'" size="mini" @click="handleUpdate(row.id)">
            编辑
          </el-button>
          <el-button size="mini" type="warning" @click="handleDel(row.id)">
            删除
          </el-button>
          <a :href="row.videoUrl" target="_blank" :download="row.title" style="margin-left: 10px;">
            <el-button type="danger" size="mini">下载</el-button>
          </a>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="fetchData"/>

    <el-dialog title="修改/新增" :visible.sync="dialogVisible" width="30%" :append-to-body='true' :close-on-click-modal="false" :show-close="false"
               :before-close="handleClose">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="课程标题">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="课程难度">
            <el-select v-model="form.rank" style="width: 100%" placeholder="请选择">
              <el-option
                v-for="item in rankOptions"
                :key="item.value"
                :label="item.value"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程分类">
            <el-select v-model="form.tagTitle" style="width: 100%" placeholder="请选择">
              <el-option
                v-for="item in tagTitleOptions"
                :key="item.value"
                :label="item.value"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程标签">
            <el-tag
              :key="tag"
              v-for="tag in tags"
              closable
              :disable-transitions="false"
              @close="handleTagsClose(tag)">
              {{tag}}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
          </el-form-item>
          <el-form-item label="课程类型">
            <el-select v-model="form.type" style="width: 100%" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.value"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程视频">
            <el-upload
              action="/api/storage/anon/upload"
              name="file"
              :limit="1"
              :on-exceed="handleExceed"
              :on-success="handleVideoSuccess"
              :file-list="fileList">
              <el-button size="mini" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="课程封面">
            <el-upload
              class="avatar-uploader"
              action="/api/storage/anon/upload"
              name="file"
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
              <img v-if="imgUrl" :src="imgUrl" style="width: 178px;height: 178px;display: block">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="课程描述">
            <el-input type="textarea" v-model="form.des"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAction">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import {getCourseList, getCourseDetail, addCourse, delCourse, updateCourse} from '@/api/course.js'
  import Pagination from 'components/pagination/pagination.vue'
  import {ERR_OK} from "@/api/config";

  export default {
    components: {Pagination},
    data () {
      return {
        list: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20
        },
        total: 0,
        query: {},
        form: {},
        inputVisible: false,
        inputValue: '',
        tags: [],
        fileList: [],
        imgUrl: '',
        tagTitleOptions: [
          {
            value: '前沿 / 区块链 / 人工智能',
          },
          {
            value: '前端 / 小程序 / JS',
          },
          {
            value: '后端 / JAVA / Python',
          },
          {
            value: '移动 / Android / iOS'
          },
          {
            value: '云计算 / 大数据 / 容器'
          },
          {
            value: '运维 / 测试 / 数据库'
          },
          {
            value: 'UI设计 / 3D动画 / 游戏'
          },
        ],
        rankOptions: [
          {
            value: '初级',
          },
          {
            value: '中级',
          },
          {
            value: '实战',
          }
        ],
        typeOptions: [
          {
            value: 'vip',
          },
          {
            value: '免费',
          },
        ],
        dialogVisible: false
      }
    },
    created () {
      //判断当前用户身份
      //如果是管理员，就加载所有；如果不是就加载属于自己的部分
      if (this.userInfo.identity != '管理员') {
        this.query.uid = this.userInfo.id;
      }
      this.fetchData()
    },
    computed: {
      // vuex
      ...mapGetters(['userInfo'])
    },
    methods: {
      handleClose() {
        this.form = {}
        this.fileList = []
        this.tags = []
        this.inputValue = ''
        this.imgUrl = ''
        this.dialogVisible = false
      },
      fetchData () {
        this.listLoading = true
        getCourseList(this.query, this.listQuery).then(response => {
          this.list = response.data.rows
          this.listLoading = false
          this.total = response.data.total
        })
      },
      submitAction() {
        this.form.tags = this.tags.toString()
        if (this.form.id == undefined) {
          // 新增
          addCourse(this.form).then(res => {
            this.$message.success('添加成功')
            this.fetchData()
          })
        } else {
          // 更新
          updateCourse(this.form).then(res => {
            this.$message.success('修改成功')
            this.fetchData()
          })
        }
        this.fetchData()
        this.dialogVisible = false
        this.handleClose()
      },
      handleCreate () {
        this.dialogVisible = true
      },
      handleUpdate (id) {
        getCourseDetail(id).then(res => {
          if (res.code == ERR_OK) {
            this.form = res.data
            this.tags = res.data.tags.split(',')
            this.imgUrl = res.data.img
            this.fileList.push({name: res.data.videoUrl.substring(7), url: res.data.videoUrl, type: res.data.videoType})
            this.dialogVisible = true
          }
        })
      },
      handleDel (id) {
        this.$confirm('你确定永久删除此条记录？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          delCourse(id).then(response => {
            this.$message.success('删除成功')
            this.fetchData();
          });
        }).catch(() => {
          this.$message.info('已取消删除')
        });
      },
      handleTagsClose(tag) {
        this.tags.splice(this.tags.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.tags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      handleAvatarSuccess(res, file) {
        if (res.code == ERR_OK) {
          this.$message.success('上传成功')
          this.form.img = res.data.url
          this.imgUrl = res.data.url
        }
      },
      handleExceed(files, fileList) {
        this.$message.warning('仅允许上传一个视频，请先删除原上传的视频文件')
      },
      handleVideoSuccess(res, file) {
        if (res.code == ERR_OK) {
          this.$message.success('上传成功')
          this.form.videoUrl = res.data.url
          this.form.videoType = res.data.type
          this.fileList.push({name: res.data.name, url: res.data.url, type: res.data.type})
        }
      }
    }
  }
</script>
<style lang="css">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
</style>
<style lang="stylus" scoped>
  @import '~assets/stylus/variables.styl';
  .course-container
    padding-top: 20px;
    .course-search
      padding: 12px 0;
      height: 60;
      .search-tag
        padding: 18px;
        font-size: 22px;
        display: inline-block;
        & > img:nth-child(2)
          margin-left: 16px;
    .el-tag + .el-tag {
      margin-left: 10px;
    }
    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .input-new-tag {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  .search-wrapper
    position: relative;
    float: right;
    width: 466px;
    height: 60px;
    line-height: 60px;
    .iconfont
      position: absolute;
      right: 15px;
      top: 20px;
      font-size: 24px;
      color: $font-four-color;
      cursor: pointer;
      line-height: 1;
    input
      padding: 0 16px;
      width: 100%;
      height: 36px;
      box-sizing: border-box;
      line-height: 36px;
      border-radius: 5px;
      outline: none;
      background: #f3f5f6;
      font-size: 14px;
      color: $font-first-color;
    .search-result
      z-index: 99;
      position: absolute;
      left: 0;
      top: 52px;
      right: 0;
      background-color: #fff;
      border-bottom-left-radius: 8px;
      border-bottom-right-radius: 8px;
      box-shadow: 0 4px 8px 0px $shadow;
      .result-item
        padding-left: 20px;
        line-height: 50px;
        color: $font-first-color;
        cursor: pointer;
        font-size: 14px;
        &:hover
          background: #f3f5f6;
</style>
